package info.rflow.model;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Document me!
 *
 * @author Holger Brandl
 */
public class WorkflowOutputCache {

    private File workingDirectory;

    Map<String, List<File>> nodeOuptuts = new HashMap<String, List<File>>();


    public WorkflowOutputCache(File workingDirectory) {

        this.workingDirectory = workingDirectory;
    }


    public void update(String name, List<File> nodeOutputFiles) {
        nodeOuptuts.put(name, nodeOutputFiles);
    }


    public static WorkflowOutputCache getCache(File workingDirectory) {
        File cacheFile = getCacheFile(workingDirectory);

        // load it if present
        WorkflowOutputCache execCache = null;

        if (cacheFile.exists()) {
            try {
                execCache = (WorkflowOutputCache) new XStream(new DomDriver()).fromXML(new FileInputStream(cacheFile));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            execCache = new WorkflowOutputCache(workingDirectory);
        }

        return execCache;
    }


    private static File getCacheFile(File workingDirectory) {
        return new File(workingDirectory, ".rflow_file_status");
    }


    public void save() {
        XStream xStream = new XStream(new DomDriver());
        try {
            xStream.toXML(this, new FileOutputStream(getCacheFile(workingDirectory)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    public List<File> getOutputs(String name) {
        if (nodeOuptuts.containsKey(name)) {
            return nodeOuptuts.get(name);
        }

        return Collections.emptyList();
    }

}
